<template>
  <div class="organizer-layout">
    <!-- 侧边栏 -->
    <el-aside :width="sidebarCollapsed ? '64px' : '240px'" class="sidebar">
      <div class="sidebar-header">
        <div v-if="!sidebarCollapsed" class="logo">
          <el-icon><Calendar /></el-icon>
          <span class="logo-text">组织者中心</span>
        </div>
        <el-button
          :icon="sidebarCollapsed ? Expand : Fold"
          @click="toggleSidebar"
          class="collapse-btn"
          text
        />
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="sidebarCollapsed"
        :unique-opened="true"
        router
        class="sidebar-menu"
      >
        <el-menu-item index="/organizer">
          <el-icon><House /></el-icon>
          <template #title>首页</template>
        </el-menu-item>
        
        <el-sub-menu index="activities">
          <template #title>
            <el-icon><Calendar /></el-icon>
            <span>活动管理</span>
          </template>
          <el-menu-item index="/organizer/activities">
            <el-icon><List /></el-icon>
            <template #title>活动列表</template>
          </el-menu-item>
          <el-menu-item index="/organizer/activities/create">
            <el-icon><Plus /></el-icon>
            <template #title>创建活动</template>
          </el-menu-item>
        </el-sub-menu>
        
        <el-menu-item index="/organizer/registrations">
          <el-icon><Tickets /></el-icon>
          <template #title>报名管理</template>
        </el-menu-item>
        
        <el-menu-item index="/organizer/feedbacks">
          <el-icon><ChatDotRound /></el-icon>
          <template #title>反馈管理</template>
        </el-menu-item>
        
        <el-menu-item index="/organizer/statistics">
          <el-icon><DataAnalysis /></el-icon>
          <template #title>数据统计</template>
        </el-menu-item>
      </el-menu>
    </el-aside>
    
    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item
              v-for="item in breadcrumbItems"
              :key="item.path"
              :to="item.path"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <!-- 通知 -->
          <el-dropdown trigger="click" @command="handleNotificationCommand">
            <el-badge :value="unreadNotifications" :hidden="unreadNotifications === 0">
              <el-button :icon="Bell" circle />
            </el-badge>
            <template #dropdown>
              <el-dropdown-menu class="notification-dropdown">
                <div class="notification-header">
                  <span>通知消息</span>
                  <el-button
                    v-if="unreadNotifications > 0"
                    type="primary"
                    size="small"
                    text
                    @click="markAllAsRead"
                  >
                    全部已读
                  </el-button>
                </div>
                <div class="notification-list">
                  <div
                    v-for="notification in notifications"
                    :key="notification.id"
                    class="notification-item"
                    :class="{ unread: !notification.read }"
                    @click="markAsRead(notification)"
                  >
                    <div class="notification-content">
                      <div class="notification-title">{{ notification.title }}</div>
                      <div class="notification-desc">{{ notification.content }}</div>
                      <div class="notification-time">{{ formatDate(notification.createTime, 'MM-DD HH:mm') }}</div>
                    </div>
                  </div>
                  <div v-if="notifications.length === 0" class="notification-empty">
                    暂无通知
                  </div>
                </div>
                <div class="notification-footer">
                  <el-button type="primary" text @click="goToNotifications">
                    查看全部
                  </el-button>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <!-- 用户菜单 -->
          <el-dropdown trigger="click" @command="handleUserCommand">
            <div class="user-info">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.name?.charAt(0) }}
              </el-avatar>
              <span v-if="!sidebarCollapsed" class="username">{{ userStore.userInfo?.name }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 主要内容 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Calendar,
  Expand,
  Fold,
  House,
  List,
  Plus,
  Tickets,
  ChatDotRound,
  DataAnalysis,
  Bell,
  ArrowDown,
  User,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const sidebarCollapsed = ref(false)
const notifications = ref([])
const unreadNotifications = ref(0)

// 当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 面包屑导航
const breadcrumbItems = computed(() => {
  const pathSegments = route.path.split('/').filter(Boolean)
  const items = [{ title: '首页', path: '/organizer' }]
  
  const routeMap = {
    'activities': '活动管理',
    'create': '创建活动',
    'edit': '编辑活动',
    'registrations': '报名管理',
    'feedbacks': '反馈管理',
    'statistics': '数据统计'
  }
  
  let currentPath = ''
  pathSegments.forEach((segment, index) => {
    if (index === 0) return // 跳过 'organizer'
    
    currentPath += `/${segment}`
    const fullPath = `/organizer${currentPath}`
    
    if (routeMap[segment]) {
      items.push({
        title: routeMap[segment],
        path: fullPath
      })
    } else if (route.meta?.title) {
      items.push({
        title: route.meta.title,
        path: fullPath
      })
    }
  })
  
  return items
})

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
  localStorage.setItem('organizer-sidebar-collapsed', sidebarCollapsed.value)
}

const loadNotifications = async () => {
  try {
    const response = await api.get('/notifications', {
      params: { size: 10 }
    })
    
    notifications.value = response.data.data?.data || []
    unreadNotifications.value = notifications.value.filter(n => !n.read).length
    
  } catch (error) {
    console.error('加载通知失败:', error)
  }
}

const markAsRead = async (notification) => {
  if (notification.read) return
  
  try {
    await api.put(`/notifications/${notification.id}/read`)
    notification.read = true
    unreadNotifications.value = Math.max(0, unreadNotifications.value - 1)
  } catch (error) {
    console.error('标记通知已读失败:', error)
  }
}

const markAllAsRead = async () => {
  try {
    await api.put('/notifications/read-all')
    notifications.value.forEach(n => n.read = true)
    unreadNotifications.value = 0
    ElMessage.success('已标记全部通知为已读')
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleNotificationCommand = (command) => {
  // 处理通知相关命令
}

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/organizer/profile')
      break
    case 'settings':
      router.push('/organizer/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '确认退出',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await userStore.logout()
        router.push('/login')
        ElMessage.success('已退出登录')
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('退出登录失败:', error)
        }
      }
      break
  }
}

const goToNotifications = () => {
  router.push('/organizer/notifications')
}

// 监听路由变化，更新面包屑
watch(
  () => route.path,
  () => {
    // 路由变化时可以执行一些操作
  }
)

onMounted(() => {
  // 恢复侧边栏状态
  const collapsed = localStorage.getItem('organizer-sidebar-collapsed')
  if (collapsed !== null) {
    sidebarCollapsed.value = collapsed === 'true'
  }
  
  // 加载通知
  loadNotifications()
  
  // 定期刷新通知
  setInterval(loadNotifications, 30000) // 30秒刷新一次
})
</script>

<style scoped>
.organizer-layout {
  height: 100vh;
  display: flex;
}

.sidebar {
  background: #001529;
  transition: width 0.3s ease;
  overflow: hidden;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #1f2937;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  font-weight: 600;
  font-size: 16px;
}

.logo-text {
  white-space: nowrap;
}

.collapse-btn {
  color: white;
  border: none;
}

.collapse-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.sidebar-menu {
  border: none;
  background: #001529;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: rgba(255, 255, 255, 0.8);
  border-bottom: none;
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background: #1890ff;
  color: white;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item) {
  background: #0c1e35;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.1);
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item.is-active) {
  background: #1890ff;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

.header-left {
  flex: 1;
}

.breadcrumb {
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.main-content {
  flex: 1;
  background: #f5f7fa;
  padding: 20px;
  overflow-y: auto;
}

/* 通知下拉菜单样式 */
.notification-dropdown {
  width: 320px;
  max-height: 400px;
  padding: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
  color: #303133;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.notification-item:hover {
  background: #f5f7fa;
}

.notification-item.unread {
  background: #f0f9ff;
  border-left: 3px solid #409eff;
}

.notification-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.notification-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.notification-desc {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
}

.notification-time {
  color: #909399;
  font-size: 12px;
}

.notification-empty {
  padding: 40px 16px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.notification-footer {
  padding: 8px 16px;
  border-top: 1px solid #e4e7ed;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .organizer-layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100% !important;
    height: auto;
  }
  
  .sidebar-header {
    justify-content: center;
  }
  
  .sidebar-menu {
    height: auto;
    display: flex;
    overflow-x: auto;
  }
  
  .sidebar-menu :deep(.el-menu-item),
  .sidebar-menu :deep(.el-sub-menu) {
    min-width: 120px;
  }
  
  .header {
    padding: 0 12px;
  }
  
  .header-right {
    gap: 8px;
  }
  
  .username {
    display: none;
  }
  
  .main-content {
    padding: 12px;
  }
  
  .notification-dropdown {
    width: 280px;
  }
}
</style>